/**
 * Copyright (C) 2015-2018 IQIYI
 * All rights reserved.
 *
 * AUTHOR(S)
 * 王海斌
 *   E-mail: wanghaibin@qiyi.com
 * 
 * VERSION
 *   Thu 08 Feb 2018 10:32:11 AM CST
 */
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>


using namespace std;

int read_data(const char * path)
{
    int fd = open(path, O_RDONLY );
    if(fd<0) {
        cout << "read data failed." << endl;
        return 0;
    }
    char tmpData[1024]={0};
    char *tmpData2 = new char[1024];
    memset(tmpData2, '\0', 1024);
    ssize_t iRead = pread( fd, tmpData ,1024, 3);
    if(0==memcmp(tmpData, tmpData2, 1024)) {
        cout << "equal empty" << tmpData << iRead << endl;
    } else {
        cout << "not equal, read=" << iRead<< endl;
    }
    close(fd);
    return 0;
}

void TestTruncate(const char *file )
{
    int fd = open(file, O_WRONLY | O_CREAT | O_TRUNC , S_IRUSR | S_IWUSR );
    if(fd<0) {
           cout << "open " << file << " failed." << endl;
           return;
    }
    int len=1024*1024;
    int iRet = ftruncate(fd,len);
    cout << "truncate errno=" << errno << " err=" << strerror(errno) 
        << " ret=" << iRet << endl;
    const char * buf = "aaa";
    int iWrite = pwrite(fd, buf, strlen(buf), 0); 
    cout << "first write ret=" << iWrite << " err=" << strerror(errno) << endl;
    /*
    iWrite = pwrite(fd, buf, strlen(buf), len-strlen(buf)-1);
    cout << "first write ret=" << iWrite << " err=" << strerror(errno) << endl;
    */

    close(fd);                                                                      
    read_data(file);
} 


int main(int argc, char *argv[])
{
    //TestTruncate("/mnt/data/aaa.txt");
    TestTruncate("./aaa.txt");
    return 0;
}
